package edc;

/**
 *
 * @author sasheto
 */
public class ChecksumCode extends Code {

    // TODO: implement
    public ChecksumCode(String data) {
        super(data);
    }

    @Override
    protected String encodeData() {
        return DataConverter.asciiToHex(super.getData());
    }

    public String generateChecksum() {
        String data = encodeData();
        int[] digit = new int[data.length()];

        for (int i = 0; i < digit.length; i++) {
            digit[i] = Integer.parseInt(data.substring(i, i + 1));
        }

        int sum = 0;

        for (int i = 0; i < digit.length; i++) {
            if (isEven(i+1)) {
                sum = sum + digit[i] * 1;
            } else {
                sum = sum + digit[i] * 16;
            }
        }

        String result = Integer.toHexString(sum);
        return result.substring((result.length() - 2), result.length()); //returns last 2 characters of result string
    }

    private boolean isEven(int i) {
        return i % 2 == 0;
    }
}